﻿fs.form = function (form) {
    form.reset = function () {
        $(fs.form.allGrayField).each(function () { this.reset(); });
    }
    /*
    Initialization all gray field
    example:    <td receive="true" receiveType="LM | YTDM1" identity="fieldID"
    */
    form.init = function (callback) {
        fs.form.allGrayField = new Array();

        $("[receive=true]").each(function () {
            var self = $(this);

            form.receiveHandler.put(form.makeEntityRow(self));
        });

        callback();
    }

    form.makeEntityRow = function (self) {

        var inputControl = self.find("input[type=text]").first();
        if (inputControl.length == 0)
            inputControl = self;

        var entity = {
            type: self.attr("type"),
            receivetype: self.attr("receivetype"),
            identity: self.attr("identity"),
            source: self.attr("source"),
            iscontrol: self.is("span"),
            field: self.attr("field"),
            equ: self.attr("equ"),
            index: self.attr("index") ? self.attr("index") : 0,
            addition: self.attr("addition") ? self.attr("addition") : '',
            digits: self.attr("digits") ? self.attr("digits") : '',
            month: self.attr("month") ? self.attr("month") : '',
            lastyear: self.attr("lastyear") ? self.attr("lastyear") : '',
            inputControl: inputControl,
            controlId: "#" + inputControl.attr("id"),
            value: "",
            set: function (v) {
                fs.util.setValue(self, v);
            },
            reset: function () {
                var value = fs.util.getValue(this.inputControl);
                if (!value)
                    this.set(0.00);
            }
        }
        entity.reset();
        return entity;
    }

    /* 
    get all current page gray field need to be receive from last month or others
    argument: args:{type:"",currentMonth:"",currentYear:"",title:""}
    */
    form.receiveGrayFieldValue = function (args, async, callback) {

        var successHandler = function (arg) {
            if (typeof callback == "undefined") {
                var actionObject = {};
                fs.util.extend(actionObject, arg.data);

                args.datasource = actionObject;
                args.handler.execute(args);

            } else {
                return callback(arg.data);
            }
        }

        async = (typeof async == "undefined") ? true : async;
        args.year = args.year ? args.year : fs.form.year;

        if (args.month == 0) {
            args.month = 12;
            args.loadFromLastYear = true;
            args.year = args.year - 1;
        }
        var defaultPar = String.format(" (Month eq {0}) and (Year eq {1}) and (CompanyCode eq '{2}')",
        args.month, args.year, fs.form.companycode);

        if (typeof args.month == "undefined") {
            defaultPar = String.format(" (Year eq {0}) and (CompanyCode eq '{1}')", args.year, fs.form.companycode);
        }
        if (fs.form.companycode.trim() == '') {
            defaultPar = String.format(" (Month eq {0}) and (Year eq {1})", args.month, args.year);
        }
        var urlPars = args.pars ? args.pars : defaultPar;

        var url = String.format(fs.sys.siteUrl + "/_vti_bin/ListData.svc/{0}?$filter={1}", args.title, urlPars) + "&timemark=" + new Date().getTime();
        if (!args.noCache)
            for (var i = 0; i < fs.util.cache.length; i++) {
                var cacheItem = fs.util.cache[i];
                if (cacheItem.source == args.title && cacheItem.year == args.year && cacheItem.month == args.month && cacheItem.companycode == fs.form.companycode) {
                    successHandler(cacheItem);
                    return;
                    break;
                }
            }

        var ajaxSuccess = function (d) {
            var cacheItem = {
                source: args.title,
                year: args.year,
                companycode: fs.form.companycode,
                loadFromLastYear: args.loadFromLastYear,
                month: args.month,
                data: d
            };
            //if (d.d.results.length > 0)
            fs.util.cache.push(cacheItem);

            successHandler(cacheItem);
        };

        $.ajax({
            url: url,
            type: "GET",
            dataType: "json",
            async: async,
            success: ajaxSuccess
        }).fail(function (e) {
            if (e.readyState == 4 && e.status == 200 && e.statusText == "OK") {
                var a = e.responseText;
                fs.util.eval("ajaxSuccess(" + a + ")");
            }
        });

    }

    form.receiveGrayFieldValueSeccuss = function (args) {
        //move to top selector month handler
        //var allFilterTypeFields = fs.util.search(fs.form.allGrayField, "type", args.type);

        $(args.handler.controls).each(function () {
            this.reset();
        });

        $(args.datasource.d.results).each(function () {
            var fieldValues = this;

            //put receive data to memory collection
            $(args.handler.controls).each(function () {
                var control = this.inputControl;
                var controlValue = 0.00;

                var CM_Value = "CM_" + this.identity;
                var YTDM1_Value = "YTDM1_" + this.identity;

                CM_Value = parseFloat(fs.util.ref(fieldValues, CM_Value));
                YTDM1_Value = parseFloat(fs.util.ref(fieldValues, YTDM1_Value));

                CM_Value = !CM_Value ? 0 : CM_Value;
                YTDM1_Value = !YTDM1_Value ? 0 : YTDM1_Value;

                controlValue = CM_Value;
                if (args.handler.type == "YTDM1")
                    controlValue += YTDM1_Value;

                if (args.handler.type == "YTDM1" && args.loadFromLastYear) {
                    this.reset();
                } else {
                    fs.util.setValue(control, controlValue, this.digits);
                }
                //control.val(controlValue.toFixed(2));
            })
        });

    }

    //获取特殊字段的值，一般是需要计算的
    form.receiveSpecialFieldValue = function (args, split) {
        split = split ? split : '&';

        if (args.field.indexOf(split) != -1) {
            var fieldType = args.field.split(split)[0];
            var fieldName = args.field.split(split)[1];
            if (fieldType.toUpperCase() == "MOVEMENT") {  //存在 类似 MOVEMENT&FieldName
                var value1 = fs.util.ref(args.obj, "LM_" + fieldName);
                var value2 = fs.util.ref(args.obj, "CM_" + fieldName);
                return (value1 - value2);
            }

            if (fieldType.toUpperCase() == "YTDM") {  //存在 类似 YTDM&FieldName   可计算YTD的值
                var value1 = fs.util.ref(args.obj, "YTDM1_" + fieldName);
                var value2 = fs.util.ref(args.obj, "CM_" + fieldName);
                return (parseFloat(value1) + parseFloat(value2));
            }
        }

        return fs.util.ref(args.obj, args.field);

    }

    form.receiveBlueFieldValueSeccuss = function (args) {
        args.item.reset();
        $(args.datasource.d.results).each(function () {
            var field = args.item.field, fieldType = "", fieldName = "";
            var value = 0.00;


            if (args.item.equ) {//如果存在需要计算的情况
                var fields = field.split(",");
                var equ = args.item.equ;
                for (var i = 0; i < fields.length; i++) {
                    var value = fs.form.receiveSpecialFieldValue({ field: fields[i], obj: this });
                    equ = equ.replace("{" + i + "}", value);
                }
                value = fs.util.eval(equ);
            }
            else {
                value = fs.form.receiveSpecialFieldValue({ field: field, obj: this });
            }


            if (args.item.receivetype.toUpperCase() == "LOADINGFILE") {
                args.item.addition = args.item.addition ? args.item.addition : "{0}/1000";
                // value = fs.util.eval(String.format(args.item.addition, value));
            }

            if (args.item.addition)
                value = fs.util.eval(String.format(args.item.addition, value));

            args.item.set(value);
        });
    }


    form.receiveLoadingFileValueSeccuss = function (args) {


        var query = $(args.item.inputControl).parents("td").attr("query");
        var rgcSource;
        if (query) {
            var queryRGC = fs.form.allRGC.filter(function (obj) {
                return obj.Category.toUpperCase() == query.toUpperCase();
            });

            args.datasource.d.results = args.datasource.d.results.filter(function (r) {
                return queryRGC.filter(function (qr) { return qr.RGC.toUpperCase() == r['RGC'].toUpperCase() }).length > 0;
            });
        }


        //累加Loading File中的相同月份值
        if (args.datasource.d.results.length > 1) {
            var itemTemplate = args.datasource.d.results[0];

            for (var i = 1; i < args.datasource.d.results.length; i++) {
                var currentItem = args.datasource.d.results[i];
                for (var field in itemTemplate) {
                    var fieldValue = itemTemplate[field];
                    fieldValue = fieldValue == null ? 0 : fieldValue;
                    var cfieldValue = currentItem[field];

                    if ((parseFloat(fieldValue) || parseFloat(fieldValue) == 0) && (parseFloat(cfieldValue) || parseFloat(cfieldValue) == 0)) {
                        fieldValue = parseFloat(fieldValue);
                        cfieldValue = parseFloat(cfieldValue);
                        itemTemplate[field] = fieldValue + cfieldValue;
                    }
                }
            }
            args.datasource.d.results = [itemTemplate];
        }
        form.receiveBlueFieldValueSeccuss(args);

        //        var query = $(args.item.inputControl).parent().parent().attr("query");
        //        var rgcSource;
        //        if (query) {
        //            var queryRGC = fs.form.allRGC.filter(function (obj) {
        //                return obj.Category.toUpperCase() == query.toUpperCase();
        //            });

        //            rgcSource = args.datasource.d.results.filter(function (r) {
        //                return queryRGC.filter(function (qr) { return qr.RGC.toUpperCase() == r['RGC'].toUpperCase() }).length > 0;
        //            });
        //        } else {
        //            rgcSource = args.datasource.d.results;
        //        }
        //        var loadingFileModifySource = { d: { results: []} };

        //        //累加Loading File中的相同月份值
        //        if (rgcSource.length >= 1) {
        //            var itemTemplate = rgcSource[0];

        //            for (var i = 1; i < rgcSource.length; i++) {

        //                var currentItem = rgcSource[i];
        //                for (var field in itemTemplate) {
        //                    var fieldValue = itemTemplate[field];
        //                    var cfieldValue = currentItem[field];

        //                    if ((parseFloat(fieldValue) || parseFloat(fieldValue) == 0) && (parseFloat(cfieldValue) || parseFloat(cfieldValue) == 0)) {
        //                        fieldValue = parseFloat(fieldValue);
        //                        cfieldValue = parseFloat(cfieldValue);
        //                        itemTemplate[field] = fieldValue + cfieldValue;
        //                    }
        //                }
        //            }


        //            loadingFileModifySource.d.results = [itemTemplate];
        //        }
        //        form.receiveBlueFieldValueSeccuss({ item: args.item, datasource: loadingFileModifySource });
    }

    form.greenFieldReceiver = function (args, obj) {
        args.title = obj.source.replace(/(^|\s+)\w/g, function (s) {
            return s.toUpperCase();
        }).replace(/\s+/g, "");
        args.month = obj.month ? obj.month : fs.form.month;
        args.year = obj.lastyear ? fs.form.year - 1 : fs.form.year;
        args.item = obj;
        fs.form.receiveGrayFieldValue(args, false);
    }

    form.loadingFileFieldReceiver = function (args, obj) {
        args.title = obj.source.replace(/(^|\s+)\w/g, function (s) {
            return s.toUpperCase();
        }).replace(/\s+/g, "");
        args.month = fs.form.month;
        args.item = obj;
        //receive loading file title
        args.title = fs.util.loadingFile.get(args.title);

        args.pars = String.format(" (Period eq '{0}') and (Year eq '{1}') and (Company eq '{2}')", args.month, fs.form.year, fs.form.companycode);
        fs.form.receiveGrayFieldValue(args, false);
    }


    form.receiveHandler = {
        handlers: [{ type: "YTDM1", single: true, execute: fs.form.receiveGrayFieldValueSeccuss, controls: [] },
                        { type: "LM", single: true, execute: fs.form.receiveGrayFieldValueSeccuss, controls: [] },
                        { type: "GREEN", single: false, receive: fs.form.greenFieldReceiver, execute: fs.form.receiveBlueFieldValueSeccuss, controls: [] },
                        { type: "LOADINGFILE", single: false, receive: fs.form.loadingFileFieldReceiver, execute: fs.form.receiveLoadingFileValueSeccuss, controls: [] }
                        ],
        get: function (t) {
            for (var i = 0; i < this.handlers.length; i++) {
                if (this.handlers[i].type.toUpperCase() == t.toUpperCase())
                    return this.handlers[i];
            }
        },
        put: function (t) {
            var handle = this.get(t.receivetype);
            handle.controls.push(t);
        }
    }

    return form;
} (fs.form || {});